<template>
  <a-modal
    title="修改产品"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="订单ID"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入订单ID"
                       v-decorator="['orderId', {rules: [{required: true, message: '请输入订单ID！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="产品"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入产品名称"
                       v-decorator="['productName', {rules: [{required: true, message: '请输入产品名称！'}]}]"/>
              <!--              <a-input placeholder="请输入产品Id" v-decorator="['materialId', {rules: [{required: true, message: '请输入产品Id！'}]}]"-->
              <!--                       v-show="true"/>-->
              <!--              <a-button type="dashed" @click="emiShow" style="width: 100%">-->
              <!--                引入产品-->
              <!--              </a-button>-->
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="序号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入序号"
                       v-decorator="['extend1', {rules: [{required: true, message: '请输入序号！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="软件版本号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入软件版本号"
                       v-decorator="['extend2', {rules: [{required: false, max: 25, message: '请输入不大于25位长度软件版本号！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="数量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input-number placeholder="请输入数量"
                              v-decorator="['number', {rules: [{required: true, message: '请输入数量！'}]}]"
                              :min="0" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="备注"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入备注"
                       v-decorator="['remark', {rules: [{required: false, max: 99, message: '请输入不大于99位长度备注！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <!--        自身BOM Table组件   -->
          <a-col :span="24">
            <a-form-item
              :validate-status="bomSelfValidate.validateStatus"
              :help="bomSelfValidate.errorMsg">
              <!--        复杂的BOM Table组件   -->
              <FCBomMaterialTable ref="bomMaterialTableSelf" :default-bom="bom"/>
            </a-form-item>
          </a-col>
          
          <!--    引入其它BOM    -->
          <a-col :span="24">
            <a-form-item>
              <a-button type="primary" @click="emsBomIndex1.show()">引入其它BOM</a-button>
              <ems-bom-index1 ref="emsBomIndex1" @ok="onBomSelected" :show-all-type-bom="true" default-bom-type=""/>
            </a-form-item>
          </a-col>
          
          <!--     其它BOM Table组件   -->
          <a-col :span="24">
            <a-form-item v-for="(item, index) in otherBoms">
              <FCBomMaterialTable :ref="'bomMaterialTable'+index" :key="index" @delete="(key)=>otherBoms.splice(key,1)"
                                  :default-bom="item"/>
            </a-form-item>
          </a-col>
        
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>


<script lang="ts">
import {Component, Ref, Vue,} from "vue-property-decorator";
import {addProduct} from "@/api/modular/main/emsordermaterial/emsOrderMaterialManage";
import {listFull as emsBomMaterialListFull} from "@/api/modular/main/emsbommaterial/emsBomMaterialManage";

import emsBomIndex1 from "@/views/main/emsbom/emsBomIndex1.vue";
import FCBomMaterialTable from "@/views/main/emsbom/FCBomMaterialTable.vue";

@Component({
  components: {
    FCBomMaterialTable, emsBomIndex1
  }
})


export default class ProgressBomEditModal extends Vue {
  @Ref() emsBomIndex1!: any
  @Ref() emsMaterialIndex1!: any
  labelCol = {
    xs: {span: 24},
    sm: {span: 5}
  }
  wrapperCol = {
    xs: {span: 24},
    sm: {span: 15}
  }
  labelColBlock = {
    xs: {span: 24},
    sm: {span: 2}
  }
  wrapperColBlock = {
    xs: {span: 24},
    sm: {span: 20}
  }
  visible = false
  confirmLoading = false
  form = this.$form.createForm(this)
  
  formModel = {}
  bomIndexVisible = false
  //  table 组件
  materialTypeList = [
    {key: 0, name: '原料'}, {key: 1, name: '线缆'}, {key: 2, name: '包材'},
  ]
  bom = {
    bomId: '',
    bomCode: '',
    bomName: '本次BOM',
    bomType: '',
    status: '',
    image: '',
    createTime: '',
    createUser: '',
    updateTime: '',
    updateUser: '',
    bomMaterials: [],
    otherBoms: [],
  }
  bomMaterial = {
    bomMaterialId: '',
    bomId: '',
    bomIdSource: '',
    bomMaterialSort: '',
    materialId: '',
    materialNumber: '',
    createTime: '',
    createUser: '',
    updateTime: '',
    updateUser: '',
  }
  bomSelfValidate = {}
  otherBoms = []
  selfBoms = []
  
  
  show(record) {
    this.visible = true
  }
  
  handleSubmit() {
    this.visible = true
    this.confirmLoading = true  //确认按钮防抖
    this.getSelfBomMaterialValue()
    const {form: {validateFields}} = this
    validateFields((errors, values) => {
      // this.confirmLoading = false
      /*
      * productModel
      * {
      *   orderId:0,
      *   number:0,
      *   productName: '',
      *   bom: {}
      * }
      * */
      if (!errors) {
        let haveNum = this.selfBoms.every((item) => {
          return item.materialNumber > 0
        })
        if (!haveNum) {
          this.$message.warning("您有数量未填写 或 有数量为0")
          this.confirmLoading = false
          console.log(this.selfBoms)
          return
        }
        values = Object.assign({bom: {bomMaterials: this.selfBoms, otherBoms: this.otherBoms}}, values)
        addProduct(values).then((res) => {
          this.confirmLoading = false
          //@ts-ignore
          if (res.success) {
            this.$message.success('新增成功')
            this.handleCancel()
            this.$emit('ok', values)
          } else {
            //@ts-ignore
            this.$message.info('新增失败：' + res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      } else {
        this.confirmLoading = false
      }
    })
  }
  
  handleCancel() {
    this.form.resetFields()
    this.visible = false
    this.bom = {
      bomId: '',
      bomCode: '',
      bomName: '本次BOM',
      bomType: '',
      status: '',
      image: '',
      createTime: '',
      createUser: '',
      updateTime: '',
      updateUser: '',
      bomMaterials: [],
      otherBoms: [],
    }
    this.otherBoms = []
  }
  
  // upload
  handleFileListStringChange(fileListString) {
    this.form.setFieldsValue({image: fileListString})
  }
  
  onBomSelected(selectedBomArray) {
    console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
    // 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
    // 同时还需要处理该BOM引用了多个原料或别的BOM的情况
    // // 表格里面显示BOM中包含的原料列表
    // 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
    // 构建BOM数据
    if (selectedBomArray.length == 0) {
      this.$message.error('没有选择BOM')
      return
    }
    if (selectedBomArray.length > 1) {
      this.$message.error('暂不支持多选BOM添加')
      return
    }
    if (selectedBomArray.length > 0) {
      let selectedBom = selectedBomArray[0]
      let bomIdSource = selectedBom.bomId
      emsBomMaterialListFull({bomIdSource}).then(res => {
        let bomMaterials = res.data
        // 构建BOM Bean
        //获取到组合bom里面的基础bom数据，重新赋值给选中项中的bomMaterials
        selectedBom.bomMaterials = bomMaterials
        this.otherBoms.push(selectedBom)
      })
    }
  }
  
  getSelfBomMaterialValue() {
    //@ts-ignore
    let tableValue = this.$refs.bomMaterialTableSelf.getTableValue()
    this.selfBoms = tableValue
    
    if (tableValue && tableValue.length > 0) {
      this.bomSelfValidate = {
        validateStatus: 'success',
        errorMsg: null,
      }
    } else {
      this.bomSelfValidate = {
        validateStatus: 'error',
        errorMsg: '物料清单不能为空',
      }
    }
    
    this.getBomTableValue()
  }
  
  getBomTableValue() {
    // bomMaterialTable
    for (let i = 0; i < this.otherBoms.length; i++) {
      let $refTable = this.$refs['bomMaterialTable' + i][0]
      this.otherBoms[i] = $refTable.getBom()
    }
    // for (const refsKey in this.$refs) {
    //   if (refsKey.startsWith('bomMaterialTable')) {
    //     let $refTable = this.$refs[refsKey]
    //     this.otherBoms.push($refTable.getTableValue())
    //   }
    // }
  }
  
  handleEmsMaterialIndex1Show() {
    this.emsMaterialIndex1.show()
  }
  
  onEmsMaterialIndex1Selected(materialRow) {
    // console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
    let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
    this.form.setFieldsValue({output: materialId})
    this.formModel = Object.assign({}, this.formModel, {output: materialId, outputObject: materialRow})
  }
  
  
}
</script>


<style scoped lang="less">

</style>